package com.app.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;
import org.springframework.stereotype.Component;


@Component
public class CustomRolesAuthorizationFilter extends AuthorizationFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
			throws Exception {
		HttpServletRequest req = (HttpServletRequest) request;
		String contextPath = req.getContextPath();
		String uri = req.getRequestURI();
		String path = new String(uri);
		
		if (path.startsWith(contextPath)) {
			path = path.substring(contextPath.length());
		}
		// 注销充许
		if (StringUtils.contains(path, "logout")) {
			return true;
		}
		// 登录地址
		if (StringUtils.equals(path, getLoginUrl())) {
			return true;
		}
		Subject subject = getSubject(request, response);
		OAuthInfo info = (OAuthInfo) subject.getSession(true).getAttribute("OAUTH_INFO");
		if (subject.getPrincipal() != null && info == null) {// 会话无效
			subject.logout();
			return false;
		}
		if (!subject.isAuthenticated()) {// 未登录
			return false;
			//return true;
		}
		if (ObjectUtils.equals("admin", info.getName())) {
			return true;
		}

		return true;
	}
}
